import {
  myRequesy
} from '../../request/api'
import {
  useShowToast
} from '../../commons/index'
import paltter from '../../platter/carc'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isSelect: false, //提交,编辑切换显示
    Page: 1, //页码
    pageSize: 10, //条数
    isNext: null, //是否有下一页
    isShow: false, //是否显示操作底部栏
    operateList: [{
        id: 0,
        color: '#1ED564',
        icon: '/static/image/broadcast.png',
        title: '开始收集',
      },
      {
        id: 1,
        color: '#2287F9',
        icon: '/static/image/redact.png',
        title: '编辑',
        url: '/pages/launch/launch'
      },
      {
        id: 2,
        color: '#1FC064',
        icon: '/static/image/share.png',
        title: '分享',
      },
      {
        id: 3,
        color: '#3C82D9',
        icon: '/static/image/details.png',
        title: '收集详情',
        url: '/pages/collect/collect'
      },
      {
        id: 4,
        color: '#303030',
        icon: '/static/image/examine.png',
        title: '查看表单',
        url: '/pages/form/form'
      },
      {
        id: 5,
        color: '#CCCCCC',
        icon: '/static/image/dustbin.png',
        title: '移入回收站',
      },
    ], //操作框数据
    isLen: false,
    dataList: [], //数据
    activeId: 0, //当前点击的ID
    isState: false, //是否收集
    activeIndex: 0, //当前索引
    isPoster: false, //是否显示海报
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.getDataList()
  },


  // 获取数据列表
  getDataList() {
    wx.showLoading({
      title: "加载中"
    })
    let that = this
    let {
      Page,
      pageSize,
      isSelect,
      isNext,
      dataList
    } = that.data
    myRequesy({
      url: 'get-index',
      data: {
        page: Page,
        page_size: pageSize,
        state: isSelect ? 1 : 0
      }
    }).then(res => {
      if (res.code === 0) {
        wx.hideLoading()
        that.setData({
          dataList: [...dataList, ...res.data],
          isNext: res.has_next,
          isLen: res.data.length
        })
      }
    })
  },

  // 登录授权
  getLogin() {
    let that = this
    wx.getUserProfile({
      desc: '获取您的用户名和头像',
      success(res1) {
        wx.login({
          success(res2) {
            let userData = {
              code: res2.code,
              nickName: res1.userInfo.nickName,
              avatarUrl: res1.userInfo.avatarUrl
            }
            myRequesy({
              url: 'Login',
              data: userData,
              method: "POST",
            }).then(res => {
              if (res.code === 0) {
                wx.setStorage({
                  data: res.data,
                  key: 'userInfo',
                  success() {
                    that.onShow()
                  }
                })
              } else if (res.code === 2001 || res.code === 2002 || res.code === 2003) {
                wx.removeStorage('userInfo')
              }
            })
          }
        })
      }
    })
  },

  headleAuthorization() {
    this.getLogin()
  },
  //最新提交 , 最新编辑 事件
  headleSelect(e) {
    if (wx.getStorageSync('userInfo')) {
      this.setData({
        isSelect: Boolean(parseInt(e.currentTarget.dataset.item)),
        dataList: [],
        Page: 1
      })
      this.getDataList()
    } else {
      this.getLogin()
    }


  },

  //打开操作框 函数
  headleToolbar(e) {
    let {
      index,
      id,
      state
    } = e.currentTarget.dataset
    let {
      dataList,
      operateList
    } = this.data
    if (dataList[index].is_start) {
      operateList[0].icon = '/static/image/pause.png'
      operateList[0].color = '#F03F3F'
      operateList[0].title = '暂停收集'
    } else {
      operateList[0].icon = '/static/image/broadcast.png'
      operateList[0].color = '#1ED564',
        operateList[0].title = '开始收集'
    }
    this.setData({
      operateList,
      activeId: id,
      isShow: true,
      isState: state,
      activeIndex: index
    })
  },

  //关闭操作框 函数
  headleClose() {
    this.setData({
      isShow: false
    })
  },

  // 操作框 函数
  headleSkip(e) {
    let {
      index,
      url
    } = e.detail
    let {
      activeId,
      isState,
      dataList,
      activeIndex,
      operateList,
      isLen
    } = this.data
    if (index === 0) {
      this.headleAmend(operateList, activeIndex, dataList, isState, activeId)
    } else if (index === 2) {
      this.setData({
        shareShow: true,
        isShow: false
      })
    } else if (index === 5) {
      this.headleRemove(dataList, activeId, activeIndex, isLen)
    } else {
      wx.navigateTo({
        url: url + '?id=' + activeId
      })
    }
  },

  //修改收集转态
  headleAmend(operateList, activeIndex, dataList, isState, activeId) {
    myRequesy({
      url: 'update-start',
      data: {
        a_id: activeId,
        state: !isState ? 'start' : 'stop'
      },
      method: 'POST'
    }).then(res => {
      if (res.code === 0) {
        if (!isState) {
          operateList[0].icon = '/static/image/pause.png'
          operateList[0].color = '#F03F3F',
            operateList[0].title = '暂停收集'
        } else {
          operateList[0].icon = '/static/image/broadcast.png'
          operateList[0].color = '#1ED564',
            operateList[0].title = '开始收集'
        }
        dataList[activeIndex].is_start = !dataList[activeIndex].is_start
        this.setData({
          isState: !isState,
          dataList,
          operateList
        })
      }
    })
  },


  // 移入回收站
  headleRemove(dataList, activeId, activeIndex, isLen) {
    myRequesy({
      url: 'update-dustbin',
      method: 'POST',
      data: {
        a_id: activeId,
        state: 1,
      }
    }).then(res => {
      if (res.code === 0) {
        useShowToast('已移除')
        dataList.splice(activeIndex, 1)
        this.setData({
          dataList,
          isShow: false,
          isLen: dataList.length
        })
      }
    })
  },


  // 关闭分享弹窗
  headleCloseShare() {
    this.setData({
      shareShow: false
    })
  },





  /* 海报区域*********************************************************************************************************** */

  // 海报
  headlePoster() {
    let that = this
    let {
      dataList,
      activeIndex,
      activeId
    } = that.data
    let car = new paltter().palette()
    let userInfo = wx.getStorageSync('userInfo')
    car.views[1].url = userInfo.avatarUrl
    car.views[2].text = userInfo.nickName
    car.views[3].url = dataList[activeIndex].banner
    car.views[4].text = dataList[activeIndex].title
    myRequesy({
      url: 'get-qrcode',
      data: {
        a_id: activeId
      }
    }).then(res => {
      if (res.code === 0) {
        car.views[5].url = res.data.qrcode
        that.setData({
          template: car,
          isPoster: true,
          shareShow: false
        })
      }
    })
  },

  // 保存
  saveImg() {
    this.saveImage()
  },

  // 海报
  onImgOK(e) {
    var that = this
    var imagePath = e.detail.path;
    that.setData({
      imagePath: imagePath
    })
  },

  // 保存海报
  saveImage() {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success: (res) => {
        that.setData({
          poster_hidden: true,
          isPoster: false
        })
        wx.showToast({
          title: '已保存到相册',
        })
        // setTimeout(() => {
        //   wx.navigateBack()
        // }, 1000)
      },
      fail() {
        wx.showModal({
          title: '保存失败！',
          content: '请检查相册访问是否授权',
          success(res) {
            if (res.confirm) {
              wx.openSetting({
                success(res) {}
              })
            } else if (res.cancel) {}
          }
        })
      }
    });
  },

  //关闭遮罩层
  headleMask() {
    this.setData({
      isPoster: false
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      Page: 1,
      is_user: wx.getStorageSync('userInfo')
    })
    if (wx.getStorageSync('userInfo')) {
      this.getDataList()
    }

    // 自定义tabBar
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      dataList: [],
      isShow: false,
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let {
      isNext,
      Page
    } = this.data
    if (isNext) {
      Page += 1
      this.setData({
        Page
      })
      this.getDataList()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let {
      activeId,
      activeIndex,
      dataList
    } = this.data
    if (res.from === 'button') {
      return {
        title: dataList[activeIndex].title,
        imageUrl: dataList[activeIndex].banner,
        path: "/pages/form/form?id=" + activeId
      }
    }
  }
})